package mobile.game.common.startup;

import mobile.game.common.config.JConfig;
import mobile.game.common.config.json.JNode;
import mobile.game.common.config.json.JPort;
import mobile.game.common.config.json.JRemote;
import mobile.game.common.config.json.JService;
import mobile.game.common.net.netty.Server;
import mobile.game.common.support.ClassFactory;
import mobile.game.common.support.ClassManager;
import mobile.game.core.Node;
import mobile.game.core.Port;
import mobile.game.core.Service;

public class Run {

	public static boolean start(String jsonFilePath, String runNodeName) {
		// 载入启动json配置
		if (!JConfig.load(jsonFilePath)) {
			System.out.println("载入配置文件失败！");
			return false;
		}

		// 设置当前进程运行node
		JConfig.SetMeNodeName(runNodeName);

		JNode jNode = JConfig.getMe();
		
		int listenPort = jNode.getListenPort();
		if (0 != listenPort) {
			// 启动网络监听
			new Server(listenPort).start();
		}

		// 启动node
		Node defNode = new Node(jNode.getName(), jNode.getAddr());

		if (null != jNode.getRemotes()) {
			for (JRemote jRemote : jNode.getRemotes()) {
				defNode.addRemoteNode(jRemote.getName(), jRemote.getAddr());
			}
		}

		// 启动配置中的Port和Service
		for (JPort jPort : jNode.getPorts()) {
			Port newPort = ClassFactory.createPort(jPort.getType(), jPort.getName());
			newPort.startup(defNode);

			ClassManager.getMe().addPort(newPort);

			for (JService jService : jPort.getServices()) {
				Service newServ = ClassFactory.createService(jService.getType(), jService.getName());
				newServ.startup(newPort);

				ClassManager.getMe().addService(newServ);
			}
		}

		defNode.startup();
		
		return true;
	}
}
